/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "led_example.h"

#define LED_INTERVAL_TIME_US 300000
#define LED_TASK_STACK_SIZE 512 //
#define LED_TASK_PRIO 26
#define GPIO_11 11 // TRIG---DT
#define GPIO_12 12 // ECHO---SCK
#define Gapvalue 430;
unsigned long Read(void);
double get_base(void);
double weight_show=0;
double base=0;
double weight=0;


    void *SCALE(const char *arg)
{
    (void)arg;
    base=get_base();
    while(1){

        weight=(Read()-base)/Gapvalue;
        if(weight>0){
        //printf("%.f g\n",weight);
        weight_show=weight;
        }
        else weight=0;
        hi_sleep(100);
    } 
    return NULL;
}
unsigned long Read(void)
{
	unsigned long value = 0;
	unsigned char i = 0;
    IotGpioValue input = 0;
	hi_udelay(2);
	//时钟线拉低 空闲时时钟线保持低电位
	IoTGpioSetOutputVal(GPIO_12,0);
	hi_udelay(2);	
	IoTGpioGetInputVal(GPIO_11,&input);
	//等待AD转换结束
	while(input)
    {
        IoTGpioGetInputVal(GPIO_11,&input);
    }
	for(i=0;i<24;i++)
	{
		//时钟线拉高 开始发送时钟脉冲
		IoTGpioSetOutputVal(GPIO_12,1);
		hi_udelay(2);
		//左移位 右侧补零 等待接收数据
		value = value << 1;
		//时钟线拉低
		IoTGpioSetOutputVal(GPIO_12,0);
		hi_udelay(2);
		//读取一位数据
        IoTGpioGetInputVal(GPIO_11,&input);
		if(input){
			value ++;
        }
	}
	//第25个脉冲
	IoTGpioSetOutputVal(GPIO_12,1);
	hi_udelay(2);
	value = value^0x800000;	
	//第25个脉冲结束
	IoTGpioSetOutputVal(GPIO_12,0);	
	hi_udelay(2);	
	return value;
}

double get_base(void){

    double sum = 0;    // 为了减小误差，一次取出10个值后求平均值。
  	for (int i = 0; i < 10; i++) // 循环的越多精度越高，当然耗费的时间也越多
    	sum += Read();  // 累加
  	return (sum/10); // 求平均值进行均差

}

static void LedExampleEntry(void)
{
    osThreadAttr_t attr;

    IoTGpioInit(GPIO_11);
    IoTGpioSetDir(GPIO_11, IOT_GPIO_DIR_IN);
    IoTGpioInit(GPIO_12);
    IoTGpioSetDir(GPIO_12, IOT_GPIO_DIR_OUT);

    attr.name = "SCALE";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = LED_TASK_STACK_SIZE;
    attr.priority = LED_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)SCALE, NULL, &attr) == NULL) {
        printf("[LedExample] Falied to create SCALE!\n");
    }
    return NULL;
}


SYS_RUN(LedExampleEntry);